var knex = require('../dbhelper').instance();
var Promise = require('bluebird');
module.exports = {
    getmenu: function (userid) {
        return new Promise(function (resolve, reject) {
            knex('vmenu').where('userid', userid||'').orderBy('showorder')
                .select('*').then(function (data) {
                    resolve(data);
                }).catch(function (error) {
                    console.error(error);
                    reject(error);
                });
        });
    },
    list: function (userid, guestid) {
        return new Promise(function (resolve, reject) {
                knex.raw('SELECT	vmenu.*, IFNULL(usermenu.id,0) checked FROM 	vmenu LEFT JOIN usermenu ON vmenu.menuid = usermenu.menuid AND usermenu.userid = ? WHERE	vmenu.userid = ? order by vmenu.parentid,vmenu.showorder',[guestid,userid]).then(function (data) {
                    resolve(data);
                }).catch(function (error) {
                    console.error(error);
                    reject(error);
                });
        });
    },
    addpermission:function (params) {
        return new Promise(function (resolve, reject) {
            knex('usermenu').insert({id:params.id,userid:params.userid,menuid:params.menuid}).then(function (data) {
                    resolve(data);
                }).catch(function (error) {
                    console.error(error);
                    reject(error);
                });
        });
    }, 
    delpermission:function (params) {
        return new Promise(function (resolve, reject) {
            knex('usermenu').where('userid',params.userid).andWhere('menuid',params.menuid).del().then(function (data) {
                    resolve(data);
                }).catch(function (error) {
                    console.error(error);
                    reject(error);
                });
        });
    },
};